package com.vvvtimes.demo.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.net.URLEncodeUtil;
import cn.hutool.extra.qrcode.QrCodeException;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vvvtimes.demo.common.dto.RestResponse;
import com.vvvtimes.demo.domain.dto.EncoderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
public class ConvertService {

    public RestResponse<String> base64Encoder(EncoderDTO encoderDTO) {
        RestResponse<String> result = new RestResponse<>();
        String data = encoderDTO.getData();
        String res = Base64.encode(data);
        result.setResult(res);
        return result;
    }


    public void jsonToExcel(String string) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        log.info(string);

        JSONArray objects = JSONObject.parseArray(string);
       if(CollectionUtil.isNotEmpty(objects)){

           //获取title
           JSONObject o = (JSONObject) objects.get(0);
           Set<String> keys = o.keySet();

           //List<T> ts = JSONObject.parseArray(s, responseType);
           try {
               this.setExcelResponseProp(response, "用户列表");

               ExcelWriter writer = new ExcelWriter(response.getOutputStream(), ExcelTypeEnum.XLSX);

               // 设置SHEET
               Sheet sheet = new Sheet(1, 0);
               sheet.setSheetName("sheet1");

               // 设置标题
               Table table = new Table(1);
               List<List<String>> titles = new ArrayList<List<String>>();
               if(CollectionUtil.isNotEmpty(keys)){
                   for(String key:keys){
                       titles.add(Arrays.asList(key));
                   }
               }
               table.setHead(titles);

               // 查询数据导出即可 比如说一次性总共查询出100条数据
               List<List<String>> userList = new ArrayList<List<String>>();
               for (int i = 0; i < objects.size(); i++) {
                   JSONObject o1 = (JSONObject) objects.get(i);
                   List<String> stringList = new ArrayList<>();
                   for(String key:keys){
                       stringList.add(String.valueOf(o1.getString(key)));
                   }
                   userList.add(stringList);
               }

               writer.write0(userList, sheet, table);
               writer.finish();


           } catch (IOException e) {
               throw new RuntimeException(e);
           }

       }
    }

    /**
     * 设置响应结果
     *
     * @param response    响应结果对象
     * @param rawFileName 文件名
     * @throws UnsupportedEncodingException 不支持编码异常
     */
    private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
